package org.csu.jpetstore_user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.codec.digest.DigestUtils;
import org.csu.jpetstore_user.entity.*;
import org.csu.jpetstore_user.persistence.AccountMapper;
import org.csu.jpetstore_user.persistence.CategoryMapper;
import org.csu.jpetstore_user.persistence.ProfileMapper;
import org.csu.jpetstore_user.persistence.UserMapper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;

@Controller
@Validated
public class AccountController {


//    @Autowired
//    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private ProfileMapper profileMapper;

    @Autowired
    private CategoryMapper categoryMapper;


    @GetMapping("/signOnForm")
    public String loginForm(){
        return "account/signon";
    }

    @GetMapping("/registerForm")
    public String registerForm(HttpSession session){
        System.out.println("用户注册......");
        QueryWrapper<Account> accountQueryWrapper = new QueryWrapper<>();
        accountQueryWrapper.eq("userid","j2ee");
        Account account = accountMapper.selectOne(accountQueryWrapper);
        session.setAttribute("account",account);
        //初始化profile为j2ee的选项
        QueryWrapper<Profile> profileQueryWrapper = new QueryWrapper<>();
        profileQueryWrapper.eq("userid","j2ee");
        Profile loginUserProfile = profileMapper.selectOne(profileQueryWrapper);
        account.initProfile(loginUserProfile);
        //将该用户的喜好信息填入session
        session.setAttribute("profile",loginUserProfile);

        //封装一下所有categories
        List<Category> categoryList = categoryMapper.selectList(null);
        session.setAttribute("categories",categoryList);
        return "account/register";
    }

    @GetMapping("/myAccountForm")
    public String myAccountForm(HttpSession session){
        User loginUser = (User) session.getAttribute("loginUser");
        //默认收货地址什么的表格信息显示的账户为j2ee
        QueryWrapper<Account> accountQueryWrapper = new QueryWrapper<>();
        accountQueryWrapper.eq("userid","j2ee");
        Account account = accountMapper.selectOne(accountQueryWrapper);
        session.setAttribute("account",account);
        session.setAttribute("message2","");
        //调取该account的profile
        QueryWrapper<Profile> profileQueryWrapper = new QueryWrapper<>();
        profileQueryWrapper.eq("userid",loginUser.getUsername());
        Profile loginUserProfile = profileMapper.selectOne(profileQueryWrapper);
        account.initProfile(loginUserProfile);
        //将该用户的喜好信息填入session
        session.setAttribute("profile",loginUserProfile);
        System.out.println("用户："+loginUser.getUsername()+" 进入个人账户页面，语言喜好为："+loginUserProfile.getLangpref());

        //封装一下所有categories
        List<Category> categoryList = categoryMapper.selectList(null);
        session.setAttribute("categories",categoryList);

        return "account/myAccountForm";
    }


    //用户登录
    @PostMapping("/login")
    public String login(HttpServletRequest request,@RequestParam("code") String code, @RequestParam("email") String email,@Validated @ModelAttribute User user, BindingResult bindingResult,
                        Model model, HttpSession session){
        System.out.println("用户名、密码和验证码为："+user.getUsername()+","+user.getPassword()+","+code);
        //登陆失败
        //1、用户名、密码输入格式不正确
//        System.out.println(bindingResult.getAllErrors());
        StringBuilder validationErrorMsg = new StringBuilder();
        if(bindingResult.hasErrors()){
            for (ObjectError error: bindingResult.getAllErrors()){
                validationErrorMsg.append(error.getDefaultMessage());
                validationErrorMsg.append(",");
            }
            model.addAttribute("loginMsg",validationErrorMsg.subSequence(0,validationErrorMsg.length()-1));
            return "account/signon";
        }

        //2、验证码不正确
        /*if(checkCode.equals("")){
            model.addAttribute("loginMsg","验证码不正确");
            return "account/signon";
        }*/
        session = request.getSession();
        String emailCode = (String) session.getAttribute("email_code");
        // 验证码比对
        if (!StringUtils.equals(code, emailCode)) {
            request.setAttribute("error", "验证码错误");
            model.addAttribute("loginMsg","验证码不正确");
            return "account/signon";
        }


        //3、数据库查询失败
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username",user.getUsername());
        User loginUser = userMapper.selectOne(userQueryWrapper);
        System.out.println(loginUser);
        if(loginUser==null){
            model.addAttribute("loginMsg","用户名不存在");
            return "account/signon";
        }
        /*else if(!DigestUtils.md5Hex(user.getPassword()).equals(loginUser.getPassword())){
            model.addAttribute("loginMsg","密码不正确");
            return "account/signon";
        }*/
        else{//4、登陆成功
            System.out.println("登陆成功......");
            QueryWrapper<Account> accountQueryWrapper = new QueryWrapper<>();
            accountQueryWrapper.eq("userid",loginUser.getUsername());
            Account account = accountMapper.selectOne(accountQueryWrapper);
            //放入账户信息
            session.setAttribute("account",account);
            //放入登录账号信息
            session.setAttribute("loginUser",loginUser);
            return "redirect:/mainForm";
        }
    }


    //用户注册
    @PostMapping("/register")
    public String register(HttpServletRequest request,@RequestParam("code") String code,@RequestParam("email") String email,@Validated @ModelAttribute User registerUser,BindingResult bindingResult,//一定要跟在@Validated的后面！！！！！！！
                           @ModelAttribute Account registerAccount, Model model,HttpSession session){
        System.out.println("用户名、密码和验证码为："+registerUser.getUsername()+","+registerUser.getPassword()+","+code);
        //用户名和密码输入格式问题
        System.out.println(bindingResult.toString());
        StringBuilder validationErrorMsg = new StringBuilder();
        if(bindingResult.hasErrors()){
            for (ObjectError error: bindingResult.getAllErrors()){
                validationErrorMsg.append(error.getDefaultMessage());
                validationErrorMsg.append(",");
            }
            model.addAttribute("registerMsg",validationErrorMsg.subSequence(0,validationErrorMsg.length()-1));
            return "account/register";
        }
        //验证码正确与否
        session = request.getSession();
        String emailCode = (String) session.getAttribute("email_code");
        // 验证码比对
        if (!StringUtils.equals(code, emailCode)) {
            request.setAttribute("error", "验证码错误");
            model.addAttribute("loginMsg","验证码不正确");
            return "account/register";
        }




        /*

        if(checkCode.equals("")){
            model.addAttribute("registerMsg","验证码不正确");
            return "account/register";
        }*/
        //查询数据库该用户名是否存在
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username",registerUser.getUsername());
        User newUser = userMapper.selectOne(userQueryWrapper);
        System.out.println(newUser);
        //存在则返回当前页面
        if (newUser!=null){
            model.addAttribute("registerMsg","用户名已存在");
            return "account/register";
        }
        //若不存在则添加用户：userinfo、account
        else{

            //向session中添加登录用户
            session.setAttribute("loginUser",registerUser);
            session.setAttribute("account",registerAccount);
            //密码使用md5数据加密
            registerUser.setPassword(DigestUtils.md5Hex(registerUser.getPassword()));
            registerAccount.setPassword(DigestUtils.md5Hex(registerAccount.getPassword()));
            System.out.println(registerAccount.getPassword());
            System.out.println(registerUser.getPassword());
            userMapper.insert(registerUser);
            accountMapper.insert(registerAccount);
            System.out.println(registerUser.getUsername()+ " 用户注册成功......");
            return "redirect:/mainForm";
        }
    }
}
